'use strict';
var restful = require('../utils/restful')
var util = require('../utils/util')

module.exports = function(Sysuser) {
    

    var loginByWxOpenId = function(appId,openid,next){
        var rest = {
            code: restful.statusCode.OK,
            msg:'success',
            error:'',
            data: null
        }

        if(!appId)
        {
            rest.code = restful.statusCode.Forbidden
            rest.msg = 'Access Denied!'
            rest.error = 'appid is not found!'
            return next(null,rest)
        }

        if(!openid)
        {
            rest.code = restful.statusCode.Forbidden
            rest.msg = 'Access Denied!'
            rest.error = 'openid is not found!'
            return next(null,rest)
        }
        
        Sysuser.find({
            where:{
                and:[
                    {
                        app_id: appId,
                        wx_openid: openid
                    }
                ]
            }
        },function(err,data_results){
            if(err)
            {
                rest.code = restful.statusCode.INVALID_REQUEST;
                rest.msg = 'openid login error!'
                rest.error = err;
                return next(null,rest);
            }

            if(data_results.length <= 0){
                rest.code = restful.statusCode.INVALID_REQUEST;
                rest.msg = 'openid no found , please registe first!'
                rest.error = err;
                return next(null,rest);
            }

            var userData = data_results[0];
            userData.createAccessToken(60*60*24,function(err,token){
                rest.data = token;
                next(null,rest);
            })
        })
    }

    Sysuser.loginByWxOpenId = loginByWxOpenId;
    Sysuser.remoteMethod('loginByWxOpenId',{
        http:{
            path:'/login/wxopenid/:appId',
            verb:'post'
        },
        accepts:[
            {
                arg:'appId',
                type:'string'
            },
            {
                arg:'openid',
                type:'string'
            }
        ],
        returns:{
            arg:'res',
            type:'object'
        }
    })
};
